/**
 * Created by 123 on 17-12-6.
 * 整改单
 */
import {commitRectifyBill, queryTaskDetail} from '../services/rectifyBill';
import {Toast} from 'antd-mobile'
import {Actions} from 'react-native-router-flux'
import moment from 'moment';
import fetch from "dva/fetch";

function showToast(msg) {
  Toast.fail(msg,3)
}

export default {
  namespace: 'rectifyBill',

  state: {
    taskSameId:'',
      hasDone:false,
      itemsIndex:0,
      dialogText:'',
    projectName: '',//工程名
    taskId: '',//任务id
    checkTime: moment(new Date()).format('YYYY-MM-DD'),//检查时间
    supervisor: '',//监督员
    supervisorImgs: [],//监督员签名
    param:[
        {
          checkPlace: '',//检测部位
          troubleSelecton:[],
          trouble: [],//发现问题[]
          currentImg: [],//现场照片
          importLevel: '',
          conductResult: '',
          rectifyTime: '',//整改时间
          rectifyContent: '',//整改要求
        }
    ],
    paramView:[],
    crops: [
      {
        name: '',//名字
        id: '',
        type: '建设单位',
        typeId: 1,
        thisChecked:false,
      },
      {
        name: '',//名字
        id: '',
        type: '施工单位',
        typeId: 2,
        thisChecked:false,
      },
      {
        name: '',//名字
        id: '',
        type: '监理单位',
        typeId: 3,
        thisChecked:false,
      }
    ],
    cropsNext: [
      {
        name: '',//名字
        id: '',
        type: '建设单位',
        typeId: 1,
        thisChecked:false,
      },
      {
        name: '',//名字
        id: '',
        type: '施工单位',
        typeId: 2,
        thisChecked:false,
      },
      {
        name: '',//名字
        id: '',
        type: '监理单位',
        typeId: 3,
        thisChecked:false,
      }
    ],
      cropsOther: [
          {
              name: '',//名字
              id: '',
              type: '勘察单位',
              typeId: 4,
              thisChecked:true,
          },
          {
              name: '',//名字
              id: '',
              type: '设计单位',
              typeId: 5,
              thisChecked:true,
          },
          {
              name: '',//名字
              id: '',
              type: '检测单位',
              typeId: 6,
              thisChecked:true,
          }
      ],
    corpImgs: [],//三方签名
    seriousGrade: [//严重等级
    ],
    handleResult: [],//
    troubleWhere: 1,// 1：建设责任单位；2：施工责任单位；3：监理责任单位
    hasChange: false,//更新数组内数据无法刷新view需更改此值用于刷新View

    showModal: false,
    typeId:''
  },

  subscriptions: {},

  effects: {
      *thisBoxChecked({payload}, {call, put, select}){
        console.log(payload,'checkbox')
          payload.param.forEach((val,index) =>{
            if(val.id === payload.id){
              val.thisChecked = !val.thisChecked
            }
          })
          yield put({type: 'checkThis', payload: payload.param})
      },
    *shenHeGouXuan({payload}, {call, put, select}){
      payload.param.forEach((val,index) =>{
        if(val.id === payload.id){
          val.thisChecked = !val.thisChecked
        }
      })
      yield put({type: 'gouXuanSuccess', payload: payload.param})
    },
    *change({payload},{put,select,call}){
      const {crops} = yield select(state =>state.rectifyBill);
      yield put({type: 'changeSuccess',payload: {data:payload,crops:crops}});
    },
    //获取任务详情
    *queryTaskDetail({payload}, {put, call, select}){
        console.log(1)
      const {res, error}=yield call(queryTaskDetail, {taskId: payload});
      if (error) {
        yield put({type:'thisDialog/thisInit'});
        yield put({type:'dialogShow',payload:'获取错误:'+error.message});
        yield put({type: 'queryFail', payload: error})
      } else {
        console.log(res,'xiafazhenggai')
        if (res.code === 1 || res.code === '1') {
          yield put({type: 'querySuccess', payload: res.data})
        } else {
          yield put({type: 'queryFail', payload: res.message})
          yield put({type:'thisDialog/thisInit'});
          yield put({type:'dialogShow',payload:'获取错误:'+res.message});
        }
      }
    },
    //下发整改单
    *commitRectifyBill({payload}, {put, call, select}){
      yield put({type:'thisHasDone'})
      const {supervisor, checkTime, taskId, crops,param,cropsNext}=yield select(state => state.rectifyBill);
      const {JDSignature, SGSignature, JLSignature, JSSignature,KCSignature,SJSignature,JCSignature}=yield select(state => state.sign);
      const {SGImgs, JSImgs, JLImgs,allImgs}=yield select(state => state.photo);
      const {projectId}=yield select(state => state.projectsList);
      let changeFrom = [];
      let ids = []
      if (JDSignature.length === 0) {
          yield put({type:'thisDialog/thisInit'});
          yield put({type:'dialogShow',payload:'请监督员签字'});
          yield put({type:'thisDidNOtDone'})
        // return;
      }else {
          // cropsOther.map((val,index) =>{
          //     crops.push(val)
          // })
          let trueNum = 0
          let trueNumShen = 0
          for (let i in crops){
              Object.assign(crops[i], param[0]);
              if(crops[i].thisChecked === true){
                trueNum += 1
              }
          }
        for (let i in cropsNext){
          Object.assign(crops[i], param[0]);
          if(cropsNext[i].thisChecked === true){
            trueNumShen += 1
          }
        }
          if(trueNum === 0){
            yield put({type:'thisDialog/thisInit'});
            yield put({type:'dialogShow',payload:'请至少选择一家单位'});
            yield put({type:'thisDidNOtDone'})
          }else if (trueNumShen===0){
            yield put({type:'thisDialog/thisInit'});
            yield put({type:'dialogShow',payload:'请至少选择一家审核单位'});
            yield put({type:'thisDidNOtDone'})
          }else {
            let fromImgs = [];
            let changeFormCorpSigns = [];
            // cropsOther.map((val,index) =>{
            //   if (val.typeId == 4) {
            //     fromImgs = allImgs;
            //     KCSignature.map((val, index) => {
            //       changeFormCorpSigns.push({url: val.url, type: 4})
            //     });
            //   }else if (val.typeId == 5) {
            //     fromImgs = allImgs;
            //     SJSignature.map((val, index) => {
            //       changeFormCorpSigns.push({url: val.url, type: 5})
            //     });
            //   }else if (val.typeId == 6) {
            //     fromImgs = allImgs;
            //     JCSignature.map((val, index) => {
            //       changeFormCorpSigns.push({url: val.url, type: 6})
            //     });
            //   }
            // })
            // cropsNext.map((val,index) =>{
            //   if (val.thisChecked){
            //     ids = ids+','+val.id
            //   }
            // })
            // ids = ids.substring(1)
            cropsNext.map((val,index) =>{
              if (val.thisChecked){
                ids.push({corpExamineId:val.id})
              }
            })
            crops.map((val, index) => {
              if (val.typeId == 1) {
                if(val.id !== ''){
                  fromImgs = allImgs;
                  JSSignature.map((val, index) => {
                    changeFormCorpSigns.push({url: val.url, type: 1})
                  });
                }
              } else if (val.typeId == 2) {
                if(val.id !== '') {
                  fromImgs = allImgs;
                  SGSignature.map((val, index) => {
                    changeFormCorpSigns.push({url: val.url, type: 2})
                  });
                }
              } else if (val.typeId == 3) {
                if(val.id !== '') {
                  fromImgs = allImgs;
                  JLSignature.map((val, index) => {
                    changeFormCorpSigns.push({url: val.url, type: 3})
                  });
                }
              }
              if(val.id !== '') {
                if (val.thisChecked === true) {
                  let problems = [];
                  if (val.troubleSelecton.length > 0) {

                    // if (val.typeId == 1) {
                    //     fromImgs = allImgs;
                    //     JSSignature.map((val, index) => {
                    //         changeFormCorpSigns.push({url: val.url, type: 1})
                    //     });
                    // } else if (val.typeId == 2) {
                    //     fromImgs = allImgs;
                    //     SGSignature.map((val, index) => {
                    //         changeFormCorpSigns.push({url: val.url, type: 2})
                    //     });
                    // } else if (val.typeId == 3) {
                    //     fromImgs = allImgs;
                    //     JLSignature.map((val, index) => {
                    //         changeFormCorpSigns.push({url: val.url, type: 3})
                    //     });
                    // }
                    // else if (val.typeId == 4) {
                    //     fromImgs = allImgs;
                    //     KCSignature.map((val, index) => {
                    //         cropSigns.push({url: val.url, type: 3})
                    //     });
                    // }else if (val.typeId == 5) {
                    //     fromImgs = allImgs;
                    //     SJSignature.map((val, index) => {
                    //         cropSigns.push({url: val.url, type: 3})
                    //     });
                    // }else if (val.typeId == 6) {
                    //     fromImgs = allImgs;
                    //     JCSignature.map((val, index) => {
                    //         cropSigns.push({url: val.url, type: 3})
                    //     });
                    // }

                    val.troubleSelecton.map((val, index) => {
                      problems.push({problem: val.content})
                    });



                  }
                  let fromItem = {
                    seriousGrade: val.importLevel,
                    handleResult: val.conductResult,
                    changeDate: moment(val.rectifyTime === '' ? new Date() : val.rectifyTime).format('YYYY-MM-DD'),
                    changeRequirement: val.rectifyContent,
                    corpId: val.id,
                    changeFormImgs: fromImgs,
                    // changeFormCorpSigns: cropSigns,
                    inspectPosition: val.checkPlace,
                    changeFormProblems: problems
                  };
                  changeFrom.push(fromItem);
                }
              }
            });
            const {userId}= yield select(state => state.login);
            let thisParam = {
              supervisor: supervisor,
              inspectDate: moment(new Date()).format('YYYY-MM-DD'),
              taskId: taskId,
              userId: userId,
              changeForms: changeFrom,
              changeFormJdzSigns: JDSignature,
              changeFormCorpSigns:changeFormCorpSigns,
              changeFormExamines:ids
            };
            console.log(thisParam,'....thisParam')
            const {res, error}=yield call(commitRectifyBill, thisParam);
            if (error) {
              console.log(error)
              yield put({type:'thisDialog/thisInit'});
              yield put({type:'dialogShow',payload:error});
              yield put({type: 'commitFail', payload: error})
              yield put({type:'thisDidNOtDone'})
            } else {
              if (res.code == 1) {
                Actions.pop();
                yield put({type: 'commitSuccess', payload: res.data});
                yield put({type: 'tasksList/queryTasks'});
                yield put({type:'thisDidNOtDone'})
                yield put({type:'thisDialog/thisInit'});
                yield put({type:'dialogShow',payload:'提交成功'});
                yield put({type:'troubleCollection/getClean'});
                yield put({type:'taskCenter/getTableList'});
                yield put({type:'getClean'})
                // showToast(res.message);
              } else {
                yield put({type: 'commitFail', payload: res.message})
                yield put({type:'thisDialog/thisInit'});
                yield put({type:'dialogShow',payload:res.message});
                yield put({type:'thisDidNOtDone'})
              }

            }
          }
      }
    },

    //显示整改单
    *showRectifyBill({payload}, {put, call, select}){
      const {supervisor, checkTime, taskId, crops,param}=yield select(state => state.rectifyBill);
      const {JDSignature, SGSignature, JLSignature, JSSignature,KCSignature,SJSignature,JCSignature}=yield select(state => state.sign);
      const {SGImgs, JSImgs, JLImgs,allImgs}=yield select(state => state.photo);
      const {projectId}=yield select(state => state.projectsList);
      let cropSigns = [];

      let  paramView = {};
      let type = ''
      let name = ''
      crops.map((val,index) =>{
        if(val.thisChecked === true){
          type = type + val.type+ '   ';
          name = name + val.name+ '   '
        }
      })
      paramView.name = name;
      paramView.type = type;

        JSSignature.map((val, index) => {
            cropSigns.push({url: val.url, type: 1})
        });
        SGSignature.map((val, index) => {
            cropSigns.push({url: val.url, type: 2})
        });
        JLSignature.map((val, index) => {
            cropSigns.push({url: val.url, type: 3})
        });
        // KCSignature.map((val, index) => {
        //     cropSigns.push({url: val.url, type: 4})
        // });
        // SJSignature.map((val, index) => {
        //     cropSigns.push({url: val.url, type: 5})
        // });
        // JCSignature.map((val, index) => {
        //     cropSigns.push({url: val.url, type: 6})
        // });
        paramView.imgs = allImgs;
        paramView.cropSigns = cropSigns;
      Object.assign(paramView, param[0]);

      yield put({type: 'setParam', payload: paramView});
      yield put({type: 'missModal', payload: payload});
    },

    //问题集添加问题
    *collectionTroubles({payload}, {put, call, select}){
        const {typeId,data}=payload;
        yield put({type: 'setTroubles', payload: {data: data, typeId: typeId}})
    },

    *getClean({payload}, {put, call, select}){
        yield put({type:'troubleCollection/getClean'});
        yield put({type:'getThisClean'});
        yield put({type:'photo/cleanPhotoImgs'});
        yield put({type:'sign/cleanSignImgs'})
    },
    *addPictures({payload}, {put, call, select}){
      let data = new FormData()
      data.append('file', {
        uri: payload.uri,
        type: 'image/jpeg',
        name: payload.name,
      });

      try {
        const res = yield fetch(GLOBAL.INT.imageUpload, {
          method: 'post',
          headers: {
            'Content-Type': 'multipart/form-data',
          },
          body: data,
        });

        const json = yield res.json();
        console.log(res,'res.....')
        const url = json.data.fileurl;

        if (url !== null) {
          yield put({type: 'photo/saveSuccess', payload: {url: url, type: payload.type}})
        }

      } catch (e) {
        console.error(e);
      }

    },
  },

  reducers: {
    setSameId(state, {payload}){
      return { ...state, taskSameId: payload}
    },
    changeSuccess(state, {payload}){
        let mParam = state.param;
        mParam[0].troubleSelecton[payload.data.index].content = payload.data.text;
        return { ...state, param: [].concat(mParam)}
    },
    commitFail(state, {payload}){
      return {...state}
    },
    commitSuccess(state, {payload}){
      return {...state}
    },
    queryFail(state, {payload}){
      return {...state}
    },
    querySuccess(state, {payload}){
      const {seriousGrade, project, task, handleResult}=payload;
      const {prjName, buildCorpName, consCorpName, superCorpName}=project;
      const {signInBys, id}=task;
      let mCrops = state.crops;
      let shenhe = state.cropsNext;
      let mParam = state.param;
      mCrops[0].name = buildCorpName;
      mCrops[1].name = consCorpName;
      mCrops[2].name = superCorpName;

      shenhe[0].name = buildCorpName;
      shenhe[1].name = consCorpName;
      shenhe[2].name = superCorpName;

      //
      let grade = [
          {
              id:'grade1',
              label:'请选择'
          }
      ];
      let result = [
          {
              id:'result1',
              label:'请选择'
          }
      ];
      seriousGrade.map(i => {
        grade.push({value: i.id, label: i.label})
      });
      handleResult.map(i => {
        result.push({value: i.id, label: i.label})
      });

      mCrops[0].id = project.buildCorp;
      mCrops[1].id = project.consCorp;
      mCrops[2].id = project.superCorp;


      shenhe[0].id = project.buildCorp;
      shenhe[1].id = project.consCorp;
      shenhe[2].id = project.superCorp;

      return {
        ...state,
        projectName: prjName,
        taskId: id,
        crops: mCrops,
        cropsNext: shenhe,
        param:mParam,
        supervisor: signInBys,
        seriousGrade: grade,
        handleResult: result,
        dialogText:''
      }
    },
    //设置监督员照片
    setSupervisorImgs(state, {payload}){
      const {typeId, data}=payload;
      return {...state}
    },
    //设置检查日期
    setCheckTime(state, {payload}){

      return {...state, checkTime: payload};
    },
    //设置检查地点
    setCheckPlace(state, {payload}){
      const {typeId, data}=payload;
      let mParam = state.param;
      mParam[0].checkPlace = data;
      return {...state, param: mParam, hasChange: !state.hasChange};
    },

    //设置问题
    setTroubles(state, {payload}){
        const {typeId, data}=payload;
        let mParam = state.param;
        if(mParam[0].troubleSelecton.length == 0 ){
            mParam[0].troubleSelecton = data;
        }else {
            for (let i in data){
                for (let j in mParam[0].troubleSelecton){
                    if (mParam[0].troubleSelecton[j].id === data[i].id) {
                        // crop.trouble = crop.trouble.c(data[a]);
                        data[i].content = mParam[0].troubleSelecton[j].content;
                        mParam[0].troubleSelecton.splice(j, 1);
                    }
                }
                mParam[0].troubleSelecton.push(data[i]);
            }
        }
        return {...state, param: mParam, hasChange: !state.hasChange};
    },
    //设置上传的问题
    setTroubleList(state, {payload}){

      return {...state};
    },
    //设置问题集位置
    setWhereTroubles(state, {payload}){
      return {...state, troubleWhere: payload,typeId:payload}
    },

    //设置现场照片
    setCurrentImg(state, {payload}){
      const {typeId, data}=payload;
      return {...state}
    },
    //设置严重等级
    changeImportLevel(state, {payload}){
      const {typeId, data}=payload;
        let mParam = state.param;
        mParam[0].importLevel = data;
        return {...state, param: mParam, hasChange: !state.hasChange};
    },

    //设置处理结果
    changeConductResult(state, {payload}){
      const {typeId, data}=payload;
        let mParam = state.param;
        mParam[0].conductResult = data;
        return {...state, param: mParam,hasChange: !state.hasChange};
    },

    //设置整改时间
    setRectifyTime(state, {payload}){
      const {typeId, data}=payload;
        let mParam = state.param;
        mParam[0].rectifyTime = data;
        return {...state, param: mParam,hasChange: !state.hasChange};
    },

    //设置整改要求
    setRectifyContent(state, {payload}){
      const {typeId, data}=payload;
        let mParam = state.param;
        mParam[0].rectifyContent = data;
        return {...state, param: mParam,hasChange: !state.hasChange};
    },
    //设置三方签名照片
    setCorpImgs(state, {payload}){
      const {typeId, data}=payload;
      return {...state}
    },
    resetData(state, {payload}){
        let param = [
            {
                checkPlace: '',//检测部位
                troubleSelecton:[],
                trouble: [],//发现问题[]
                currentImg: [],//现场照片
                importLevel: '',
                conductResult: '',
                rectifyTime: '',//整改时间
                rectifyContent: '',//整改要求
            },

        ];
        let data = [
            {
                name: '',//名字
                id: '',
                type: '建设单位',
                typeId: 1,
                thisChecked:false,
            },
            {
                name: '',//名字
                id: '',
                type: '施工单位',
                typeId: 2,
                thisChecked:false,
            },
            {
                name: '',//名字
                id: '',
                type: '监理单位',
                typeId: 3,
                thisChecked:false,
            }
        ]


      return {...state, crops: data,param:param}
    },

    //设置关闭整改单
    missModal(state, {payload}){

      return {...state, showModal: payload}
    },
      dialogShow(state,{payload}){
          return {...state,dialogText:payload}
      },
      addOneItem(state,{payload}){
        let itemsIndex = state.itemsIndex;
        let param = {
            id:itemsIndex,
            content:'',
            level:''
        };
        let mParam = state.param;
        mParam[0].troubleSelecton = mParam[0].troubleSelecton.concat([param]);
        return {...state,param:[].concat(mParam),itemsIndex:itemsIndex+1}
      },
      clearThisItem(state,{payload}){
          let mParam = state.param;
          for (let i in mParam[0].troubleSelecton){
              if(mParam[0].troubleSelecton[i].id === payload.id){
                  mParam[0].troubleSelecton.splice(i, 1);
              }
          }
          return {...state,param:[].concat(mParam)}
      },
      checkThis(state,{payload}){
          return {...state, crops: [].concat(payload)}
      },
    gouXuanSuccess(state,{payload}){
      return {...state,cropsNext:[].concat(payload)}
    },
      setParam(state,{payload}){
          return {...state,paramView:[].concat(payload)}
      },
      thisHasDone(state,{payload}){
          return {...state,hasDone:true}
      },
      thisDidNOtDone(state,{payload}){
          return {...state,hasDone:false}
      },
      getThisClean(state,{payload}){
          return {...state,
              hasDone:false,
              itemsIndex:0,
              dialogText:'',
              projectName: '',//工程名
              taskId: '',//任务id
              checkTime: moment(new Date()).format('YYYY-MM-DD'),//检查时间
              supervisor: '',//监督员
              supervisorImgs: [],//监督员签名
              param:[
                  {
                      checkPlace: '',//检测部位
                      troubleSelecton:[],
                      trouble: [],//发现问题[]
                      currentImg: [],//现场照片
                      importLevel: '',
                      conductResult: '',
                      rectifyTime: '',//整改时间
                      rectifyContent: '',//整改要求
                  }
              ],
              paramView:[],
              crops: [
                  {
                      name: '',//名字
                      id: '',
                      type: '建设单位',
                      typeId: 1,
                      thisChecked:false,
                  },
                  {
                      name: '',//名字
                      id: '',
                      type: '施工单位',
                      typeId: 2,
                      thisChecked:false,
                  },
                  {
                      name: '',//名字
                      id: '',
                      type: '监理单位',
                      typeId: 3,
                      thisChecked:false,
                  }
              ],
            cropsNext: [
              {
                name: '',//名字
                id: '',
                type: '建设单位',
                typeId: 1,
                thisChecked:false,
              },
              {
                name: '',//名字
                id: '',
                type: '施工单位',
                typeId: 2,
                thisChecked:false,
              },
              {
                name: '',//名字
                id: '',
                type: '监理单位',
                typeId: 3,
                thisChecked:false,
              }
            ],
              corpImgs: [],//三方签名
              seriousGrade: [//严重等级
              ],
              handleResult: [],//
              troubleWhere: 1,// 1：建设责任单位；2：施工责任单位；3：监理责任单位
              hasChange: false,//更新数组内数据无法刷新view需更改此值用于刷新View

              showModal: false,
              typeId:'',
            cropsOther: [
              {
                name: '',//名字
                id: '',
                type: '勘察单位',
                typeId: 4,
                thisChecked:true,
              },
              {
                name: '',//名字
                id: '',
                type: '设计单位',
                typeId: 5,
                thisChecked:true,
              },
              {
                name: '',//名字
                id: '',
                type: '检测单位',
                typeId: 6,
                thisChecked:true,
              }
            ],
          }
      },
  },

}